package com.example.androidcoursedesign;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivityExample extends AppCompatActivity implements View.OnClickListener {
    private  OkHttpClient client;
    private ImageView imageView;

    //定义一个handler对象，用来接收子线程传输过来的数据
    private Handler handler = new Handler(Looper.myLooper()){
        //收消息
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case  108:
                    Bitmap obj = (Bitmap) msg.obj;
                    imageView.setImageBitmap(obj);
                    break;
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_exmaple);
        Button get_bt = findViewById(R.id.get_bt);
        Button post_json_bt = findViewById(R.id.post_json_bt);
        Button load_image_bt = findViewById(R.id.load_image_bt);
        imageView = findViewById(R.id.image_iv);
        load_image_bt.setOnClickListener(this);
        get_bt.setOnClickListener(this);
        post_json_bt.setOnClickListener(this);
        //1.创建OkhttpClient对象
        client = new OkHttpClient();

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id){
            case R.id.get_bt:
                //get请求
                //2.创建request对象，设置一个url地址，请求方式
                Request request1 = new Request.Builder()
                        .get()
                        .url("https://www.baidu.com")
                        .build();
                //3.创建一个call对象，参数就是request对象
                Call call = client.newCall(request1);
                
                //同步请求，因为Android不允许UI线程执行网络请求的耗时操作，需要把这个请求放到子线程去执行
                //execute(call);
                
                //异步请求方式，它会自己创建一个子线程执行网络请求
                enqueue(call);
                break;
            case R.id.post_json_bt:
                //POST 请求-json
                //构造 RequestBody 需要指定MediaType，用于描述请求/响应 body 的内容类型
                MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
                String uploadData = "{\"name\":\"李四\",\"age\":\"28\"}";
                String url = "http://10.111.34.2:8085/okhttp/toJson";

                //创建request请求
                Request request2 = new Request.Builder()
                        //post请求，请求数据放到Body中
                        .post(RequestBody.create(uploadData, mediaType))
                        .url(url)
                        .build();
                //发起请求
                client.newCall(request2).enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        Log.i("network",e.getMessage());
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        String data = response.body().string();

                        Log.i("network","返回的数据："+data);
                    }
                });
                break;
            case  R.id.load_image_bt:
                String imageUrl ="https://p.qqan.com/up/2022-4/16499029534815519.jpg";
                Request request3 = new Request.Builder()
                        .url(imageUrl)
                        .get()
                        .build();
                client.newCall(request3).enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        Log.i("network",e.getMessage());
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                         //拿到返回的输入流
                        InputStream in = response.body().byteStream();
                        //通过BitmapFactory把输入转成Bitmap对象，即要显示的图片
                        Bitmap bitmap = BitmapFactory.decodeStream(in);
//                        //在主线程中操作UI
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                //然后将Bitmap设置到 ImageView 中
//                                imageView.setImageBitmap(bitmap);
//                            }
//                        });

                        //handler传递消息
                        //创建Message对象
                        Message msg = Message.obtain();
                        msg.obj=bitmap;
                        msg.what=108;
                        //发送消息
                        handler.sendMessage(msg);

                    }
                });



                break;
        }

    }

    private void enqueue(Call call) {
        call.enqueue(new Callback() {
            //请求失败
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.i("network",e.getMessage());
            }
            //请求成功
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String dataContent = response.body().string();
                Log.i("network","返回的数据："+dataContent);


            }
        });
    }

    private void execute(Call call) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                Response response = call.execute();
                String responseContent = response.body().string();
                Log.i("network","返回的数据："+responseContent);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }
}